package com.karateca.columbiaimports;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * This class starts the download process from the command line. The process has
 * the following parameters:
 * Start Date. The starting date for the search.
 * End Date. The end date for the search.
 * Data Dir. The directory where the output files will be written.
 * Thread Count. The nunmber of cuncurrent threads downloading data.
 * Batch Size. The number of imports that will be downloaded before writing to the
 * temporary output file.
 * Skip List. A list of two-letter country codes that will not be downloaded.
 * @author Andres Dominguez
 */
public class Main
{
    /** Apache log. */
    private static final Log log = LogFactory.getLog(Main.class);

    /**
     * Start the import download process.
     * @param args the command line arguments
     */
    public static void main(String[] args) throws Exception
    {
        String startDate = "01/01/2005";
        String endDate = "03/01/2005";
        List<String> skipCountryList;
        String dataDir;
        int threadCount;
        int downloadBatchSize;
        DownloadStatistics statistics;

        log.info("Version 2.5");

        // Check number of inputs. If there is an error print usage
        if (args.length < 5)
        {
            System.err.println("Usage: java -jar importaciones.jar startDate endDate dataDir threadCount downloadBatchSize [skip country] ...");
            System.exit(1);
        }

        startDate = args[0];
        endDate = args[1];
        dataDir = args[2];
        threadCount = Integer.parseInt(args[3]);
        downloadBatchSize = Integer.parseInt(args[4]);
        // add elements to skip country list
        skipCountryList = new ArrayList<String>();
        for (int i = 5; i < args.length; i++)
        {
            skipCountryList.add(args[i]);
        }
        statistics = new DownloadStatistics(0);
        log.info("Start date: " + startDate);
        log.info("End date: " + endDate);
        log.info("Data dir: " + dataDir);
        log.info("Threads: " + threadCount);
        log.info("Download batch size: " + downloadBatchSize);
        log.info("Skip countries: " + skipCountryList);
        runConsole(startDate, endDate, dataDir, threadCount, downloadBatchSize, skipCountryList);
        log.info("Process done, time: " + statistics.getRunningTime());
    }

    /**
     * Run the process from console.
     * @param startDate start search date.
     * @param endDate end search date.
     * @param dataDir direcotry where files will be written.
     * @param threadCount number of simultaneous download threads.
     * @param downloadBatchSize Number of countries that are downloaded at a time.
     * @param skipList list of countries not to be downloaded.
     * @throws java.lang.Exception in case of error.
     */
    private static void runConsole(String startDate, String endDate, String dataDir, int threadCount, int downloadBatchSize, List<String> skipList) throws
            Exception
    {
        DownloadHandler downloadHandler;
        List<String> skipCountryList;

        // Get list of completed country to skip
        skipCountryList = getCompletedCountries(dataDir);
        skipCountryList.addAll(skipList);
        downloadHandler = new DownloadHandler(startDate, endDate, dataDir, threadCount, downloadBatchSize, skipCountryList);
        downloadHandler.startDownload();
    }

    /**
     * Returns a list of existing countries in the data directory. These countries
     * will not be downloaded again.
     * @param dataDir directory with output files.
     * @return a list of country codes existing in the data dir.
     */
    private static List<String> getCompletedCountries(String dataDir)
    {
        List<String> completedCountries = new ArrayList<String>();
        File directory;
        String fileName;

        log.info("Looking for existing files in " + dataDir);

        // Get all the names of files in the directory
        directory = new File(dataDir);
        if (directory.exists())
        {
            for (File file : directory.listFiles())
            {
                // check if it is a file and if it ends with csv before adding it to the list
                if (file.isFile())
                {
                    fileName = file.getName();
                    if (fileName.endsWith("csv") || fileName.endsWith("bz2"))
                    {
                        log.info("Found existing file " + fileName);
                        completedCountries.add(fileName.substring(0, 2));
                    }
                }
            }
        }

        return completedCountries;
    }
}
